package org.rambadger.command.validation;

import org.apache.log4j.Logger;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Collection;
import java.util.regex.Pattern;


public class UrlIdentifierValidator implements ConstraintValidator<UrlIdentifier, String> {
    UrlIdentifier constraint = null;

    @Override
    public void initialize(UrlIdentifier constraintAnnotation) {
        constraint = constraintAnnotation;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        boolean isValid = true;
        if (value.length() < constraint.minLength() || constraint.maxLength() < value.length()) {
            String message = String.format("Identifiers must be between %d and %d characters long. Value '%s' is %d characters long.", constraint.minLength(), constraint.maxLength(), value, value.length());
            context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
            isValid = false;
        }

        if (!Pattern.matches(constraint.regexp(), value)) {
            String message = String.format("Identifiers may consist of lowercase letters, numbers, underscores, and hyphens; and must begin with a letter.");
            context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
            isValid = false;
        }

        return isValid;
    }

    public static class UrlIdentifierCollectionValidator implements ConstraintValidator<UrlIdentifier, Collection<String>> {
        UrlIdentifierValidator validator;

        public UrlIdentifierCollectionValidator() {
            validator = new UrlIdentifierValidator();
        }

        @Override
        public void initialize(UrlIdentifier constraintAnnotation) {
            validator.initialize(constraintAnnotation);
        }

        @Override
        public boolean isValid(Collection<String> values, ConstraintValidatorContext context) {
            boolean isValid = true;
            for (String value : values) {
                isValid = isValid && validator.isValid(value, context);
            }
            return isValid;
        }
    }
}
